package com.chen.utils;

import com.chen.entity.bean.FastDFSFile;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Properties;

/**
 * 文件上传工具类
 *
 * @author chenchao
 * @date 2022/7/29 20:56
 */
@SuppressWarnings("all")
public class FastDFSUtil {

    private static Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);

    //读取配置文件并初始化
    static {
        try {
            /*String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            System.out.println(filePath);
            ClientGlobal.init(filePath);*/
           /* String filePath = System.getProperty("user.dir") + "/src/main/resources/fdfs_client.conf";
            ClientGlobal.init(filePath);*/

        /*    Properties props = new Properties();
            props.put(ClientGlobal.PROP_KEY_TRACKER_SERVERS,"106.12.121.73:22122");
            props.put(ClientGlobal.PROP_KEY_CONNECT_TIMEOUT_IN_SECONDS,3);
            props.put(ClientGlobal.PROP_KEY_NETWORK_TIMEOUT_IN_SECONDS,30);*/

           /* String properties = "fdfs_client.properties";
            ClientGlobal.initByProperties(properties);*/
          /*  String filePath = Thread.currentThread().getContextClassLoader()
                    .getResource("fdfs_client.conf").getPath();
            ClientGlobal.init(filePath);*/
            Properties props = new Properties();
            props.put(ClientGlobal.PROP_KEY_TRACKER_SERVERS,"106.12.121.73:22122");
            props.put(ClientGlobal.PROP_KEY_CONNECT_TIMEOUT_IN_SECONDS,3);
            props.put(ClientGlobal.PROP_KEY_NETWORK_TIMEOUT_IN_SECONDS,30);
            ClientGlobal.initByProperties(props);


        } catch (Exception e) {
            logger.error("FastDFS Clent init Fail", e);
        }
    }

    /**
     * 生成storage客户端
     *
     * @return
     * @throws IOException
     */
    private static StorageClient getStorageClient() throws IOException {
        TrackerServer trackerServer = getTrackerServer();
        return new StorageClient(trackerServer, null);

    }


    /**
     * 生成服务器端tracker
     * 追踪服务
     *
     * @return
     * @throws IOException
     */
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        return trackerClient.getTrackerServer();
    }


    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String[] upload(FastDFSFile file) {
        logger.info("File Name:" + file.getName() + "File length:" + file.getContent().length);

//        文件属性
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", file.getAuthor());
        long start = System.currentTimeMillis();
        String[] uplaodResult = null;
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();

//         上传文件
            uplaodResult = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (Exception e) {
            logger.error("上传失败,File Name", file.getName(), e);
        }
        logger.info("上传时间：" + (System.currentTimeMillis() - start) + "ms");

//    验证上传结果
        if (uplaodResult == null && storageClient != null) {
            logger.error("上传失败" + storageClient.getErrorCode());

        }

//    上传成功返回相应信息
        logger.info("上传成功，group_name" + uplaodResult[0] + ",remoteFileName:" + uplaodResult[1]);
        return uplaodResult;

    }


    /**
     * 下载文件
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {

        try {
            StorageClient storageClient = getStorageClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(fileByte);

            return ins;
        } catch (Exception e) {
            logger.error("下载失败:" + e);
        }

        return null;

    }

    /**
     * 删除文件
     * @param groupName
     * @param remoteFileName
     */
    public static  void deleteFile(String groupName, String remoteFileName){

        try {
            StorageClient storageClient = getStorageClient();
            int i = storageClient.delete_file(groupName, remoteFileName);
            logger.info("删除成功"+i);

        } catch (Exception e) {
            logger.error("删除失败："+e);
        }
    }

    /**
     * 获取文件信息
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static FileInfo getFeil(String groupName, String remoteFileName){
        try {
            StorageClient storageClient = getStorageClient();
            FileInfo file_info = storageClient.get_file_info(groupName, remoteFileName);
            return file_info;

        } catch (Exception e) {
            logger.error("获取文件失败"+e);
        }
        return null;
    }

    /**
     * 获取上传文件的完整路径
     * @return
     * @throws IOException
     */
    public static String getTrackerUrl() throws IOException, Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);

        return "http://"+storeStorage.getInetSocketAddress().getHostString()+":8888/";
    }


    public  static String[] upload(MultipartFile file){
        String name = file.getOriginalFilename();
        StorageClient storageClient =null;
        String[] uplaodResult = null;

        try {
            storageClient = getStorageClient();

//         上传文件
            uplaodResult = storageClient.upload_file(file.getBytes(), name.substring(name.lastIndexOf(".")+1),null);


        } catch (Exception e) {
            logger.error("上传失败,File Name", file.getName(), e);
        }

        if (null==uplaodResult){
            logger.error("上传失败,File Name", storageClient.getErrorCode());

        }
        return uplaodResult;
    }

}

